<?php
/**
 * Created by PhpStorm.
 * User: chenyuz
 * Date: 2019/3/5
 * Time: 15:41
 */
namespace app\ops\controller;

use app\exception\CustomException;
use app\model\JobWelfare;
use think\Db;

class Jobs extends Base{

    function index(){

        $query = request()->get();

        $where = [];

        if($query['search']) $where['c.name'] = ['like', "%{$query['search']}%"];

        $list = Db::name("job")
            ->alias('j')
            ->join("company c", "c.id = j.company_id")
            ->where($where)
            ->field("j.id, j.name, j.num, j.pay, j.address, j.mobile, j.status, j.publish_time, j.type, c.name as company_name")
            ->order("j.status, j.id desc")->paginate(10);
        $this->assign("list", $list);
        $this->assign("query", $query);
        return $this->fetch();
    }

    public function detail($id) {

        $detail = \db('job')->where(['id'=> $id])->find();
        $detail['detail'] = str_replace("cichuhuanhang", "<br/>", $detail['detail']);

        $this->assign('data', $detail);
        return $this->fetch();

    }

    function setstatus(){

        $id = request()->post('id', 0);
        $status = request()->post('status', 0);
        $reason = request()->post('reason', '');

        $post = [
            'status'=> $status
        ];

        if($status == 4){
            $post['reason'] = $reason;
        }

        db('job')->where(['id'=> $id])->update($post);
        if($status == 2){
//            $cate_id = db('job')->where(['id'=> $id])->value('cate_id');
//            db('job_category')->where(['id'=> $cate_id])->update(['status'=> 1]);
        }

        return success([]);
    }

    function add(){

        $post = request()->post();

        if($post){

            Db::startTrans();
            try{


                list($lat, $lng) = explode(',', $post['lat']);

                $cate_id = db('job_category')->where(['name'=> $post['cate_id']])->value('id');
                if(!$cate_id){
                    $cate_id = \db('job_category')->insertGetId(['name'=> $post['cate_id'], 'status'=> 0]);
                }

                $company_id = db('company')->where(['name'=> $post['company_id']])->value('id');
                if(!$company_id){
                    $company_id = \db('company')->insertGetId([
                        'name'=> $post['company_id'],
                        'status'=> 6,
                        'address'=> $post['address'],
                        "lat"=> $lat,
                        "lng"=> $lng,
                        "mobile"=> $post['mobile'],
                        "area_tag"=> $post['area_tag']
                    ]);
                }else{
                    \db('company')->update([
                        "id"=> $company_id,
                        "mobile"=> $post['mobile'],
                        "area_tag"=> $post['area_tag']
                    ]);
                }

                $pay_info = \db('job_pay')->where(['name'=> $post['pay_id']])->field('name, min, max')->find();
                if($pay_info){
                    $min = $pay_info['min'];
                    $max = $pay_info['max'];

                }else{
                    if(strrpos($post['pay_id'], '-') !== false){
                        $arr = explode('-', $post['pay_id']);

                        $min = $arr[0];
                        $max = $arr[1];

                    }else{
                        $dd = $this->str2num($post['pay_id']);
                        $min = $dd['min'];
                        $max = $dd['max'];
                    }
                }

                $data = [
                    "name"=> $post['cate_id'].$post['num']."人",
                    "pay"=> $post['pay_id'].'/月',
                    "min"=> $min,
                    "max"=> $max,
                    "address"=> $post['address'],
                    "lat"=> $lat,
                    "lng"=> $lng,
                    "cate_id"=> $cate_id,
                    "p_id"=> 0,
                    "c_id"=> 0,
                    "county_id"=> 0,
                    "company_id"=> $company_id,
                    "num"=> $post['num'],
                    "mobile"=> $post['mobile'],
                    "detail"=> $post['detail'],
                    "status"=> 2,
                    "is_send"=> 1,
                    "pay_id"=> $post['pay_id'],
                    "area_tag"=> $post['area_tag'],
                    "type"=> 2,
                    "publish_time"=> date('Y-m-d H:i:s'),
                    "valid_time"=> $post['day']*86400

                ];

                if($post['job_id']){

//                    $count = \db('job')->where(['id'=> $post['job_id'], 'company_id'=> $post['company_id']])->count();
//                    if(!$count){
//                        throw new CustomException("UNAUTHORIZED_OPERATION");
//                    }

                    db('job')->where(['id'=> $post['job_id']])->update($data);
                    db('job_tag')->where(['job_id'=> $post['job_id']])->delete();

                    $job_id = $post['job_id'];

                }else{

                    $job_id = \db('job')->insertGetId($data);
                }

                $tag = [];
                if($post['w_id']) $w_id_arr  =  explode(',', $post['w_id']);
                foreach ($w_id_arr as $v){
                    $tag[] = [
                        'job_id'=> $job_id,
                        'w_id'=> $v
                    ];
                }

                if($tag) \db('job_tag')->insertAll($tag);

                // 增加排序

                $sort_data = \db('company_sorted')->where(['company_id'=> $data['company_id']])->find();
                $max = \db('company_sorted')->max('sort');
                if($sort_data)
                {
                    \db('company_sorted')->where(['id'=> $sort_data['id']])->update([
                        'sort'=> $max + 1
                    ]);
                }else{
                    \db('company_sorted')->insert([
                        'sort'=> 1,
                        'company_id'=> $data['company_id']
                    ]);
                }

                Db::commit();


            }catch (\Exception $exception){
                Db::rollback();
            //echo $exception->getMessage();
                return fail($exception->getMessage());
            }

            return success([]);



        }else{
//            dump($this->params());
            $this->assign('params', $this->params());
            return $this->fetch();

        }


    }

    function params(){

        $category = db('job_category')->where([])->field('id, name')->select();

        $pay = db('job_pay')->where(['status'=> 1])->field('id, name')->select();

        $area = \app\model\Area::getChildren(0);

        $wel = JobWelfare::allData();

        $company = \db('company c')
            ->join('company_sorted s', 'c.id = s.company_id', 'left')
            ->where(['c.status'=> ['in', [3, 6]]])
            ->field("c.id as company_id, c.mobile, c.name,c.lat,c.lng,c.address ")
            ->order("s.sort desc , c.id desc")
            ->select();

        return [
            'category'=> $category,
            'pay'=> $pay,
            'area'=> $area,
            'welfare'=> $wel,
            'company'=> $company
        ];


    }

    function edit($id){

        $data = \db('job')->where(['id'=> $id])->find();

        $w_id = db('job_tag')->where(['job_id'=> $id])->column("w_id");

        $param = $this->params();

        foreach ($param['welfare'] as &$v){

            if(in_array($v['id'], $w_id)){
                $v['is_check'] = 1;
            }

        }

        $data['detail'] = str_replace("cichuhuanhang", "\n", $data['detail']);

        $company = array_column($param['company'], "name", 'company_id');
        $category = array_column($param['category'], "name", 'id');

        $this->assign('data', $data);
        $this->assign('params', $param);
        $this->assign('company', $company[$data['company_id']]);
        $this->assign('category', $category[$data['cate_id']]);
        $this->assign('pay', str_replace("/月", "", $data['pay']));

        return $this->fetch('add');

    }

    function str2num($str){

        $max = $min = 0;

        if(strrpos($str, '以上') !== false){

            $min = str2num(str_replace('以上', '', $str));
            $max = 99999999;

        }elseif (strrpos($str, '以下') !== false){

            $max = str2num(str_replace('以下', '', $str));
            $min = 0;

        }

        return [
            'min'=> $min,
            'max'=> $max
        ];

    }

    function search($company_name = 0)
    {
        $data = \db('company')->where(["name"=> $company_name])->field("id as company_id, mobile, name,lat,lng,address, area_tag ")->find();

        return success($data);
    }

    function company($keyword = '', $company_id = 0)
    {
        $data = \db('company c')
            ->join('company_sorted s', 'c.id = s.company_id', 'left')
            ->where(['c.status'=> ['in', [3, 6]], 'c.name'=> ['like', "%$keyword%"]])
            ->field("c.id as company_id, c.mobile, c.name,c.lat,c.lng,c.address ")
            ->order("s.sort desc , c.id desc")
            ->select();

        return success($data);
    }


}